package cn.devices.utils;


import cn.devices.security.AuthUserDetail;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class JwtUtil {
    private static final String TOKEN_SECRET="DD5654D654DSD5S1D65S4D65S1D";
    public static final String TOKEN_PREFIX = "DEVICES_";
    public static final String HEADER_STRING = "X-Token";
    private static final long EXPIRATION = 24*3600L;
    public static String createJWT(AuthUserDetail auth ) {
        //指定签名的时候使用的签名算法，也就是header中的 算法
       //生成JWT的时间

        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        StringBuffer as = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            as.append(authority.getAuthority())
                    .append(",");
        }
        //创建payload的私有声明(根据特定的业务需要添加，如果要拿这个做验证,一般是需要和JWT的接受方提前沟通)
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("authorities",as);
        claims.put("username",auth.getUsername());
        claims.put("userId",auth.getUserId());
         return Jwts.builder()
                        .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET)
                        .setSubject(auth.getUsername())
                        .setClaims(claims)
                        .setIssuedAt(new Date())
                        .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                        .compact();

    }

    public static AuthUserDetail parseJWT(String token){

        token=token.substring(JwtUtil.TOKEN_PREFIX.length());
        Claims claims=Jwts.parser()
                .setSigningKey(TOKEN_SECRET)
                .parseClaimsJws(token)
                .getBody();
        String userId=claims.get("userId").toString();
        String username = claims.get("username").toString();//获取当前登录用户名


        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
        AuthUserDetail detail=new AuthUserDetail();

        detail.setUsername(username);
        detail.setUserId(userId);
        //User user=new User(username,"",authorities==null?new ArrayList<>():authorities);

       return detail;

    }


    public static boolean verify(String token){

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
        SecretKeySpec key = new SecretKeySpec(TOKEN_SECRET.getBytes(),signatureAlgorithm.getJcaName());
        try{
            Jwts.parser().setSigningKey(key)
               .parseClaimsJws(token).getBody();
            return true;
        }catch (Exception e){
            return false;
        }

    }
}
